package com.byl.sdk.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 上传下载工具类
 * @ProjectName: tools
 * @Package: com.hjf.tools
 * @Author: niu
 * @CreateDate: 2018/3/7 10:13
 * @Version: 1.0
 */
public class UploadUtils {

   static Logger logger= LoggerFactory.getLogger(UploadUtils.class);
    private static final int NORMAL_WIDTH_SIZE = 900;
    private static final int NORMAL_HEIGHT_SIZE = 360;
    public static final String defaultType = "tms";


    public static String uploadFile(HttpServletRequest request, String type, MultipartFile file) {
        return toUpload(request, type, file);
    }

    public static String uploadImage(HttpServletRequest request,String type, MultipartFile file,int width,int height) {
        String path=toUpload(request, type, file);
        toZoomIn(request,path,width,height,0,0);
        return path;
    }

    public static String uploadBanner(HttpServletRequest request,  MultipartFile file,int width,int heigth,int min_width,int min_height){
        String path=toUpload(request,"banner",file);
        toZoomIn(request,path,width,heigth,min_width,min_height);
        return path;
    }

    /**
     * 生成缩略图
     * @param request
     * @param path
     * @param width
     * @param height
     */
    static void toZoomIn(HttpServletRequest request,String path,int width,int height,int min_width,int min_height){
        // 获得项目的路径
        ServletContext sc = request.getSession().getServletContext();
        String rootPath=sc.getRealPath("/");
        File tmp = new File(rootPath+path);
        try {
            Thumbnails.of(tmp)
                    .size(width, height)
                    .outputQuality(1)
                    .toFile(new File(rootPath+path));
            //生产缩略图
            if(min_width>0 && min_height>0){
                int pos=path.lastIndexOf(".");
                String ext=path.substring(pos);
                String prefix=path.substring(0,pos);
                 String mini=prefix+".mini"+ext;
                Thumbnails.of(tmp)
                        .size(min_width, min_height)
                        .outputQuality(1)
                        .toFile(new File(rootPath+mini));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    private static String toUpload(HttpServletRequest request, String type, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUIDUtils.generateUUID();
        String child = StringUtil.isEmpty(type) ? defaultType : type;
        String relPath = "/attachment/" + child + "/";
       String rs= copy(request,relPath,newFileName,ext,file);
        return rs;
    }


    /**
     * @param filePath 完整的要下载的文件的路径
     * @param fileName 文件的名称
     * @param response 响应流
     * @return 执行结果
     * @throws UnsupportedEncodingException
     * @Description 文件下载:
     * 读取文件到流中,然后通过输出流输出
     */
    public static boolean downloadFile(String filePath, String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        Boolean result = false;
        //目标一:将文件从电脑中读入到流中
        File file = new File(filePath);
        if (file.exists()) {
            response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes(), "iso-8859-1"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                //目标一:将文件从电脑中读入到流中
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    //目标二:通过输出流输出
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                    result = true;
                }
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }



    /**
     *
     * @param relPath 文件存放相对路径
     * @param newFileName  新文件名
     * @param ext 文件后缀
     * @param file 上传的文件
     * @return 文件的大小
     */
    static String copy(HttpServletRequest request,String relPath,  String newFileName, String ext,MultipartFile file) {
        // 获得项目的路径
        ServletContext sc = request.getSession().getServletContext();
        // 目标二: 文件保存路径
        String ymd = DateUtils.formatDateDay(Calendar.getInstance().getTime());
        String serverPath = relPath + ymd + "/";
        String path = sc.getRealPath(serverPath) + "/";
        logger.info("上传路径："+path);
        System.out.println("上传路径："+path);
        File f = new File(path);
        if (!f.exists())
            f.mkdirs();
        File tmp = null;
        if (!file.isEmpty()) {
            try {
                tmp = new File(path + "//" + newFileName + ext);
                FileOutputStream fos = new FileOutputStream(tmp);
                //目标三: 输入流
                InputStream in = file.getInputStream();
                byte[] buffer = new byte[1024 * 8];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return serverPath + newFileName + ext;
    }
}